package model.decoder;

import java.util.ArrayList;

import model.OnScreen;
import model.camera.CameraManager;
import model.location.ReferencePoint;
import android.hardware.Camera.Size;
import android.os.AsyncTask;

public abstract class Decoder<ResultType> extends AsyncTask<byte[], Void, ResultType[]>
{
	private static final String TAG = Decoder.class.getSimpleName();
	
	protected Size _previewSize;
	
	@Override
	protected ResultType[] doInBackground(byte[]... params) 
	{
		Thread.currentThread().setName(String.format("AsyncTask: %s", TAG));
		return null;
	}

	@Override
	protected void onPostExecute(ResultType[] results) 
	{
		ArrayList<ReferencePoint> refPoints = new ArrayList<ReferencePoint>();
		
		if(hasResult(results))
		{
			for (ResultType result : results) 
            {
				if(result == null)
					continue;
				if(isRightFormat(getDecodedData(result)))
					refPoints.add(createReferencePoint(result));
				else
					OnScreen.getInstance().notifyScreenWithToast("Invalid code found");
            }
			//Log.d(TAG, String.format("Results found: %d", results.length));
		}
		
//		Log.d(TAG, String.format("correct results: %d", refPoints.size()));
		OnScreen.getInstance().updateReferencePointList(refPoints);
		
		CameraManager.addCallbackBuffer();
	}
	
	protected abstract String getDecodedData(ResultType result);
	
	protected abstract ReferencePoint createReferencePoint(ResultType result);
	
	protected boolean hasResult(ResultType[] results)
	{
		if(results == null)
			return false;
		if(results.length == 1)
		{
			OnScreen.getInstance().notifyScreenWithToast("1 code");
			return true;
		}
		
		return results.length >= 2;
	}
	
	protected boolean isRightFormat(String result)
	{
		return result.matches("[-]?[0-9]+[_][-]?[0-9]+[_][-]?[0-9]+");
	}
}
